<template>
  <div class="app-container" style="background-color: #F0F2F5">
    <!--    style="background-color: #F0F2F5"-->
    <el-container>
      <el-header class="filter-container">
        <el-input v-model="input_toolbar" placeholder="请输入内容" style="width: 200px; " class="filter-item"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="onSearch" style="width: 90px;" class="filter-item">搜索
        </el-button>
        <el-button type="primary" icon="el-icon-plus" @click="onCreate(0)" class="filter-item">新建</el-button>
      </el-header>
      <el-main>
        <el-row :gutter="12" class="tenant-card">
          <el-col :span="6" v-for="(item,index) in tenantList" :key="item.id">

            <el-card shadow="hover" body-style="{border='3px'}">
              <div slot="header" class="box-card-header">
                <div style="float: left">
                  <span>{{ item.tenant_name }}</span>
                </div>
                <div style="float: right">
                  <i class="el-icon-s-tools" @click="onTenantEdit(1,item)"></i>
                </div>
              </div>
              <div class="tenant-card-area">
                <!--                card 数据列表-->
                <ol class="tenant-card-ol">
                                    <li>租户ID：<span class="tenant-card-span">【{{item.tenant_id}}】</span></li>
                  <!--                  <li>学段：<span class="tenant-card-span">{{findObjByProp('kcode',item.stage,STAGE).label}}</span></li>-->
                  <li>学段：
                    <el-tag :type="stageStyle[getNumStage(item.stage)]">
                      {{ findObjByProp('kcode', item.stage, STAGE).label }}
                    </el-tag>
                  </li>
                  <li>地区：<span
                    class="tenant-card-span">{{ item.province + '-' + item.city + '-' + item.city_area }}</span>
                  </li>
                  <li>套餐：<span
                    class="tenant-card-span">{{
                        findObjByProp( 'kcode',item.order, orderType).name
                    }}</span>
                  </li>
                  <li>用户量：<span class="tenant-card-span">{{ item.stu_num }}</span></li>
                  <li>缴费比例：<span class="tenant-card-span">80%</span></li>
                  <li>视频量：<span class="tenant-card-span">{{ item.video_num }}</span></li>
                  <li>公开量：<span class="tenant-card-span">{{ item.video_open_num }}</span></li>
                  <li>
                    <div style="vertical-align: middle; ">
                      <el-divider></el-divider>
                      开/关
                      <el-switch

                        style="padding: 0;margin: 0"
                        v-model="item.isTenant_onoff"
                        active-color="#13ce66"
                        @change="onTenantOnOff(item,index)"
                      >
                      </el-switch>
                      <el-button type="text " style="float:right; color: #F56C6C;padding: 0;margin: 0"
                                 @click="onDelete(item,index)">删除
                      </el-button>
                    </div>
                  </li>
                </ol>
              </div>
            </el-card>

          </el-col>
        </el-row>
        <!--      创建租户面板-->
        <el-dialog
          :title="dialogTitle[dialogType]"
          :visible.sync="isCreateTenant"
          :close-on-click-modal=false>
          <el-form
            ref=""
            :model="tenantCardInfo"
            :rules="rules"
            label-width="100px"
            style=" width: 80%; margin-left:50px;">
            <el-form-item label="租户名称：" prop="tenant_name">
              <el-input v-model.trim="tenantCardInfo.tenant_name"></el-input>
            </el-form-item>
            <el-form-item label="学段：" prop="order">
              <el-select v-model="tenantCardInfo.stage" placeholder="请选择学段">
                <el-option v-for="(item,index) in STAGE"
                           :label="item.label"
                           :value="item.kcode">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="套餐：" prop="order">
              <el-select v-model="tenantCardInfo.order" placeholder="请选择套餐">
                <el-option v-for="(item,index) in orderType"
                           :label="item.name"
                           :value="item.kcode">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="地区：">
              <v-distpicker @selected="onSelect" :province="tenantCardInfo.province" :city="tenantCardInfo.city"
                            :area="tenantCardInfo.city_area"></v-distpicker>

            </el-form-item>
            <div style="text-align:right;">
              <el-button @click="cancelTenant">取消</el-button>
              <el-button type="primary" @click="confirmAddTenant">确定</el-button>
            </div>
          </el-form>

        </el-dialog>
      </el-main>

    </el-container>
  </div>
</template>

<script>

import VDistpicker from 'v-distpicker'
import { getOrders, updateOrder } from '@/api/basicmgt'
import { updateTenant, addTenant, deleteTenant, getTenants } from '@/api/tenant'
import { findObjByProp } from '@/utils/utilc'
import { addStructure } from '@/api/hxy'

/**
 *租户信息目录
 */
const defaultTenant = {
  id: '',
  tenant_id: '',
  tenant_name: '',
  create_at: '',
  update_at: '',
  create_by: '',
  update_by: '',
  stu_num: '0',
  tea_num: '0',
  order: '',
  city_area: '桥西区',
  city: '石家庄市',
  province: '河北省',
  video_num: '0',
  video_open_num: '0',
  stage: '',
  isTenant_onoff: false//租户启用状态
}

export default {
  components: { VDistpicker },
  name: 'tenant',
  data() {
    return {
      rules: {
        tenant_name: [{ required: true, message: '不能为空', trigger: 'blur' }],
        order: [{ required: true, message: '请选择套餐', trigger: 'blur' }]
      },

      stageStyle: ['success', 'warning', 'danger'],

      input_toolbar: '',//搜索栏
      tenantList: [],
      dialogType: '0',
      dialogTitle: ['创建租户', '编辑租户'],
      tenantCardInfo: Object.assign({}, defaultTenant),
      isCreateTenant: false,

      tenantInfo_Form: {
        tenant_name: '',
        order: '',
        isTenant_onoff: false
      },

      // orderType: ['A', 'B', 'C'],
      orderType: this.$global.ORDER_TYPE,
      STAGE: []

    }
  },

  created() {
    this.getStages()
    this.getOrders()
    this.getTenants()

  },
  methods: {

    async getTenants() {

      const res = await getTenants()

      if (res.data.length > 0) {
        for (let i = 0; i < res.data.length; i++) {
          let temp = Object.assign({}, defaultTenant)
          this.server_data_convert(temp, res.data[i], 1)
          // console.log(JSON.stringify(temp))
          this.tenantList.push(temp)
        }

      }
      // console.log('res==' + JSON.stringify(res.data))



    },

    async getStages() {
      this.STAGE = await this.$global.STAGE()
    },
    async getOrders() {
      const res = await getOrders()
      let orderList = res.data

      console.log("tancan=="+JSON.stringify(res.data))

      this.$global.ORDER_TYPE = []
      for (let i = 0; i < orderList.length; i++) {
        this.$global.ORDER_TYPE.push(orderList[i])
      }
      this.orderType = this.$global.ORDER_TYPE
    },

    onCreate(type) {
      // this.$message('submit!')

      this.dialogType = type
      this.isCreateTenant = true
      this.tenantCardInfo = Object.assign({}, defaultTenant)

      // this.tenantList.push(this.tenantCardInfo)
      // this.$message('创建租户' + this.tenantList.length)

    },
    onSelect(data) {

      console.log(JSON.stringify(data))

      this.tenantCardInfo.province = data.province.value
      this.tenantCardInfo.city = data.city.value
      this.tenantCardInfo.city_area = data.area.value
    },

    onSubmit_CreateTenant() {
      this.$message('创建租户')
    },
    onCancel_CreateTenant() {
      this.isCreateTenant = false
    },

    onSearch() {
      this.$message('租户页搜索')
    },

    async onTenantOnOff(_tenant, index) {
      // console.log('删除租户：' + JSON.stringify(_tenant))

      let server = {}
      this.server_data_convert(_tenant, server, 0)
      const { code, msg } = await updateTenant(server.tenantId, server)
      if (code == '20000') {
        if (_tenant.isTenant_onoff) {
          _tenant.isTenant_onoff = true
          this.$message({
            type: 'success',
            message: '租户启用'
          })
        } else {
          _tenant.isTenant_onoff = false
          this.$message({
            type: 'error',
            message: '租户停用'
          })
        }
      } else {
        new Error(msg || 'Error')

      }

      // if ( this.tenantList[index].isTenant_onoff) {
      //   this.tenantList[index].isTenant_onoff = true
      //   this.$message('租户启用')
      // } else {
      //   this.tenantList[index].isTenant_onoff = false
      //   this.$message('租户停用')
      // }
    },

    /**
     * 编辑租户
     *
     * */
    async onTenantEdit(type, item) {
      // this.$message('租户管理')
      this.dialogType = type
      this.isCreateTenant = true
      this.tenantCardInfo = item
      // let stur = await this.$global.GET_HXY_STRUCTURE()
      // console.log("组织结构："+JSON.stringify(stur))

    },

    /**
     * 删除租户
     *
     * */
    onDelete(item, index) {

      // console.log('删除租户：' + JSON.stringify(item))


      // const  _tenant = item;
      this.$confirm('确定要删除租户吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(
        async() => {
        console.log('删除租户：' + item.tenant_id)
        await deleteTenant(item.tenant_id)
        // await deleteOrder(item.id)
        this.tenantList.splice(index, 1)
        this.$message({
          type: 'success',
          message: 'Delete success !'
        })
      })
        .catch(err => {
          console.error(err)
        })

    },

    /**
     * 本地数据和服务器数据格式转换
     *
     * @param local 本地数据
     * @param server 服务端数据
     * @param type 转换类型 1 服务端转本地 other：本地转服务端
     *
     *
     * */
    server_data_convert(local, server, type) {
      if (type == 1) {
        local.id = server.id ,
          local.tenant_id = server.tenantId,
          local.tenant_name = server.tenantName ,
          local.create_at = server.createTime ,
          local.update_at = server.updateTime ,
          local.create_by = server.createBy,
          local.update_by = server.updateBy,
          local.order = server.orderType ,
          local.city_area = server.cityArea,
          local.city = server.city ,
          local.province = server.province ,
          local.stage = server.stage ,
          local.isTenant_onoff = server.active == 0 ? false : true
      } else {
        server.id = local.id,
          server.tenantId = local.tenant_id,
          server.tenantName = local.tenant_name,
          server.createTime = local.create_at,
          server.updateTime = local.update_at,
          server.createBy = local.create_by,
          server.updateBy = local.update_by,
          // server.id = local.stu_num,
          // server.id = local.tea_num,
          server.orderType = local.order,
          server.cityArea = local.city_area,
          server.city = local.city,
          server.province = local.province,
          // server.id = local.video_num,
          // server.id = local.video_open_num,
          server.stage = local.stage,
          server.active = local.isTenant_onoff ? 1 : 0
      }

    },

    /***
     * 创建租户
     */
    async confirmAddTenant() {

      let diaType = this.dialogType
      let server = {}
      this.server_data_convert(this.tenantCardInfo, server, 0)
      // console.log("craete=="+JSON.stringify(server))

      if (diaType == 0) {

        // const { data } = await addTenant(this.tenantCardInfo)
        const { data } = await addTenant(server)

        // addStructure({display_name:data.tenantId}).then(res=>{
        //
        //   console.log("创建组织架构："+res.message+"==="+res.params.id)
        //
        // })

        console.log('tianjia：' + data.tenantId)
        this.tenantCardInfo.id = data.id
        this.tenantCardInfo.tenant_id = data.tenantId
        // console.log('创建==' + JSON.stringify(this.tenantCardInfo))
        this.tenantList.push(this.tenantCardInfo)

      } else {
        const { code, msg } = await updateTenant(server.tenantId, server)

        // console.log("res=="+JSON.stringify(code))

        if (code == '20000') {
          // await updateTenant(this.tenantCardInfo.id, this.tenantCardInfo)
          for (let index = 0; index < this.tenantList.length; index++) {
            if (this.tenantList[index].id === this.tenantCardInfo.id) {
              this.tenantList.splice(index, 1, Object.assign({}, this.tenantCardInfo))
              break
            }
          }
        } else {
          new Error(msg || 'Error')
        }

      }
      this.cancelTenant()
    },

    /**
     * 取消创建租户
     */
    cancelTenant() {
      this.isCreateTenant = false
    },

    // getOrders() {
    //
    //   if (this.tenantList.length <= 0) {
    //
    //   }
    //
    // },

    getObjectByProp(key, propname, array) {

      let arr = array.filter(
        function(order) {
          if (order[propname] == key) {
            // console.log("orderlist="+order.order_name+'   ,'+key)
            return order
          }
        }
      )

      if (arr.length > 0) {
        return arr[0]

      } else {
        return undefined
      }

    },

    findObjByProp(pname, value, array) {
      return findObjByProp(pname, value, array)
    },

    getNumStage(kcode) {
      return kcode.substr(kcode.length - 1, 1)

    }

  }
}


</script>

<style lang="scss" scoped>
.app-container {
  min-height: 1080px;
  width: 100%;
  display: block;
  position: relative;
}

.el_row {
  display: flex;
  flex-wrap: wrap;
}

.el-card {
  min-width: 100%;
  min-height: 100%;
  transition: all .5s;
  padding: 2px;
  margin-bottom: 20px;
  /*&:hover{*/
  /*  background-color: #F2F6FC;*/
  /*}*/
}


.box-card-header {
  position: relative;
  height: 30px;
  font-size: 20px;
  /*font-size: larger;*/
  font-family: 'Open Sans', Arial, sans-serif;
  /*background-color: #4AB7BD;*/
  /*img{*/
  /*  width: 50%;*/
  /*  height: 100%;*/
  /*  transition: all 0.2s linear;*/
  /*}*/
}

.tenant-card-area {
  /*float: left;*/
  /*width: 100%;*/
  /*height: 100%;*/
  /*position:absolute;*/
  /*display: block;*/

}

.tenant-card-ol {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 80%;
  list-style: none;
  /*background-color: #4AB7BD;*/

}

.tenant-card-ol li {
  margin-top: 5px;
}
</style>
